package com.clss.emergencycall.utils;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.clss.emergencycall.base.Constant;
import com.clss.emergencycall.utils.SpHelper;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by LiuV on 2017/6/23.
 */

public class UploadHelper {
	private static final String TAG = "UploadHelper";
	public static final int IMAGE_FROM_LOCAL = 111;
	public static final int VIDEO_FROM_LOCAL = 222;

	/**
	 *  h5文件上传
	 * @param file
	 * @param url
	 * @param type
	 * @param callback
	 */
	public static void uploadFile(File file, String url, int fileType, int type, Callback callback) {
		if (file == null) {
			return;
		}
		RequestBody requestBody;
		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
		if(fileType == Constant.UPLOAD_FILE_TYPE_PHOTO){
			requestBody = RequestBody.create(MediaType.parse(Constant.IMAGE), file);
		} else if(fileType == Constant.UPLOAD_FILE_TYPE_VIDEO){
			requestBody = RequestBody.create(MediaType.parse(Constant.VIDEO), file);
		} else if(fileType == Constant.UPLOAD_FILE_TYPE_VOICE ){
			requestBody = RequestBody.create(MediaType.parse(Constant.AUDIO), file);
		} else {
			requestBody = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
		}
		MultipartBody body = null;
		try {
			body = builder.addFormDataPart("type", type+"")
					.addFormDataPart("files", URLEncoder.encode(file.getName(),"UTF-8"), requestBody)
					.build();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Request request = new Request.Builder().url(url)
				.post(body)
				.addHeader(Constant.APP_TOKEN,
						SpHelper.getInstance().getToken())
				.build();
		new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(callback);
	}



	//从本地相册选择照片上传
	public static void selectImageFromStore(Activity context, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		context.startActivityForResult(intent, requestCode);
	}

	//从本地相册选择视频上传
	public static void selectVideoFromStore(Activity context, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
		context.startActivityForResult(intent, requestCode);
	}
	/**
	 * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
	 */
	public static String getImageAbsolutePath(Context context, Uri imageUri) {
		if (context == null || imageUri == null) {
			return null;
		}

		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT &&
				DocumentsContract.isDocumentUri(context, imageUri)) {
			if (isExternalStorageDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			} else if (isDownloadsDocument(imageUri)) {
				String id = DocumentsContract.getDocumentId(imageUri);
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[]{split[1]};
				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		} // MediaStore (and general)
		else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(imageUri)) {
				return imageUri.getLastPathSegment();
			}
			return getDataColumn(context, imageUri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			return imageUri.getPath();
		}
		return null;
	}

	private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = {column};
		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return null;
	}

	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	private static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	private static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	private static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}
}
